import {messages} from "share/common";
import React from 'react';
import { connect } from 'react-redux'
import config from 'config'
import { Modal, Button, Tabs, Upload, Icon, message, Table } from 'antd'
const TabPane = Tabs.TabPane;
import httpFetch from 'share/httpFetch'
import FileSaver from 'file-saver'
const { confirm } = Modal;

//数据导入组件
class Importer extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      visible: false,
      fileList: [],
      uploading: false,
      tabKey: 'UPDATE',
      result: {},
      transactionID: null,
      errorColumns: [
        {title: messages('components.key471'/*行号*/), dataIndex: 'index', width: '13%'},
        {title: messages('components.key472'/*错误信息*/), dataIndex: 'error'}
      ],
      resultDom:null,
      errorData: [],
      downloading: false,
      isFirst: true,
      initFlag: null,
    };
  }

  componentWillReceiveProps(nextProps) {
    if(this.props.visible!=nextProps.visible){
      this.setState({ visible: nextProps.visible, tabKey: 'UPDATE' })
    }
    if (nextProps.tabKey) {
      this.setState({tabKey: nextProps.tabKey})
    }
  }

  showConfirm = mess => {
    confirm({
      title: messages('components.key464')/*提示*/,
      content: mess,
      width: 'auto',
      okText: messages('components.key1048')/*已有员工存在信用分或信用事件，是否覆盖导入*/,
      cancelText: messages('components.key960')/*跳过*/,
      onOk: () => {
        this.setState({ initFlag: true, isFirst: false }, this.handleOk)
      },
      onCancel: () => {
        this.setState({ initFlag: false, isFirst: false }, this.handleOk)
      },
    });
  };

  handleOk = () => {
    const { tabKey, fileList } = this.state;
    const { noTransaction, uploadParams, accept } = this.props;
    //在导入tab下为上传
    if(tabKey === 'UPDATE'){
      if(!fileList || fileList.length === 0){
        message.error(messages('components.key490'/*请选择文件后，再导入*/))
        return;
      }
      if (accept) {
        let isFileType = true; //符合文件格式
        if (accept === '.xlsx') {
          fileList.map(item => {
            //fixbug 41468: 一些操作系统的文件MIME type值为""，所以加上name的判断
            if (item.type !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' && !/\.xlsx$/.test(item.name)) {
              isFileType = false
            }
          });
        }
        if (!isFileType) {
          message.error(messages('components.key842')/*上传失败，文件格式错误*/);
          return
        }
      }
      const formData = new FormData();
      fileList.forEach((file) => {
        formData.append('file', file);
      });
      uploadParams && Object.keys(uploadParams).map(key => {
        formData.append(key, uploadParams[key])
      });
      //第一次不需要initFlag参数
      if (this.props.haveConfirm && !this.state.isFirst) {
        formData.append('initFlag', this.state.initFlag)
      }
      this.setState({
        uploading: true,
      });
      //导入数据
      httpFetch.post(this.props.uploadUrl, formData, {"Content-type": 'multipart/form-data'}).then(res => {
        if(this.props.isImporterResultDom){
          let result = this.props.callBackResult(res.data);
          this.setState({tabKey:'SUCCESS',fileList: [],uploading: false,resultDom: result.resultDom});
          return;
        }

        if(this.props.listentSwitch) {
          this.setState({
            fileList: [],
            tabKey: 'SUCCESS',
            uploading: false,
            isFirst: true,
            result: {successEntities:1}
          })
          this.props.onOk(res.data.transactionID || res.data.transactionOID || res.data.transactionUUID || res.data);
          if(res.data.failNum){
            message.success(messages('components.key785',{arg1:res.data.successNum,arg2:res.data.failNum})/*付款成功{arg1}条，失败{arg2}条*/);
          }else{
            message.success(messages('components.key660',{arg1: 1}/*导入成功：{arg1}条*/));
          }
        } else if(noTransaction){
          let errorData = [];
          res.data.error.map(item => {
            Object.keys(item).map(key => {
              errorData.push({
                error: key,
                index: item[key].join()
              })
            })
          });
          this.setState({
            tabKey: 'SUCCESS',
            uploading: false,
            isFirst: true,
            fileList: [],
            result: {
              successEntities: res.data.successEntity,
              failureEntities: res.data.failEntity
            },
            errorData
          })
        } else{
          this.setState({ transactionID: res.data.transactionID || res.data.transactionOID || res.data.transactionUUID || res.data },() => {
            this.listenStatus()
          });
        }
      }).catch(e => {
        this.setState({ uploading: false, isFirst: true });
        //是否需要二次确认
        if (this.props.haveConfirm && this.state.isFirst && e.response && e.response.data && e.response.data.errorCode === 'CREDIT_002') {
          this.showConfirm( e.response.data.message);
          return;
        }
        if(e.response && e.response.data && e.response.data.message){
          message.error(e.response.data.message);
        } else {
          message.error(messages('components.key475'/*导入失败，请重试*/))
        }
      })
    } else {
      this.props.onOk(this.state.transactionID);
      this.setState({
        visible: false
      })
    }
  };

  //监听导入状态：PARSING_FILE(1001), PROCESS_DATA(1002), DONE(1003), ERROR(1004), CANCELLED(1005)
  listenStatus = () => {
    const { isSpecial } = this.props;
    httpFetch.get(`${this.props.listenUrl}/${this.state.transactionID}`).then(res => {
      if (res.data.status === 1004) {
        if(isSpecial){
          this.setState({
            fileList: [],
            tabKey: 'SUCCESS',
            uploading: false,
            result: res.data
          })
        } else {
          this.setState({ uploading: false });
          message.error(messages('components.key475'/*导入失败，请重试*/))
        }
      } else if (res.data.status !== 1003) {
        setTimeout(() => {
          this.listenStatus()
        }, 1000)
      } else {
        this.setState({
          fileList: [],
          tabKey: 'SUCCESS',
          uploading: false,
          result: res.data
        }, () => {
          let errorData = [];
          let errors = this.state.result.errors || {};
          Object.keys(errors).map(error => {
            errors[error].map(index => {
              errorData.push({index, error})
            })
          });
          errorData.sort((a,b) => a.index > b.index);
          errorData = errorData.slice(0, 10);
          this.setState({ errorData })
        })
      }
    }).catch(() => {
      this.setState({ uploading: false });
      message.error(messages('components.key475'/*导入失败，请重试*/))
    })
  };

  onCancel = () => {
    this.setState({visible: false, uploading: false, fileList: [], isFirst: true,});
    if (this.state.transactionID) {
      httpFetch.delete(`${config.budgetUrl}/api/budget/batch/transaction/logs/${this.state.transactionID}`)
    }
  };

  //下载导入模板
  downloadTemplate = () => {
    this.setState({
      downloading: true,
    });
    let {downFileExtension} =this.props;
    let hide = message.loading(messages('components.key476'/*正在生成文件..*/));
    httpFetch.get(this.props.templateUrl, {}, {}, {responseType: 'arraybuffer'}).then(res => {
      let b = new Blob([res.data], {type: "file"});
      let name = this.props.downFileName;
      FileSaver.saveAs(b, `${name}${downFileExtension}`);
      hide();
      this.setState({
        downloading: false,
      });
    }).catch(() => {
      this.setState({
        downloading: false,
      });
      message.error(messages('components.key477'/*下载失败，请重试*/));
      hide();
    })
  };

  //下载错误信息
  downloadErrors = () => {
    let {downFileExtension} =this.props;
    let hide = message.loading(messages('components.key476'/*正在生成文件..*/));
    let url = this.props.errorUrl + `/${this.state.transactionID}`;
    httpFetch.get(url, {}, {}, {responseType: 'arraybuffer'}).then(res => {
      let b = new Blob([res.data], {type: "file"});
      let name = messages('components.key472'/*错误信息*/);
      FileSaver.saveAs(b, `${name}${downFileExtension}`);
      hide();
    }).catch(() => {
      hide();
      message.error(messages('components.key491'/*错误信息下载失败，请检查导入模板是否正确*/));
    })
  };

  //只能上传一个文件
  handleChange = (info) => {
    let fileList = info.fileList;
    fileList = fileList.reverse().slice(-1);
    this.setState({ fileList })
  };
  //切换导入Tab页
  switchingTab = (tab) => {
    this.setState({
      tabKey: tab
    })
  }

  handleAfterClose = () => {
    this.setState({
      tabKey: 'UPDATE',
      uploading: false,
      fileList: [],
      isFirst: true,
    });
    this.props.afterClose();
  };

  render() {
    const { title, uploadUrl, fileName, accept, noTransaction, isSpecial, hasTable } = this.props;
    const { visible, uploading, tabKey, result, errorColumns, errorData, importerResultDom,resultDom } = this.state;
    const props = {
      action: uploadUrl,
      onRemove: (file) => {
        this.setState(({ fileList }) => {
          const index = fileList.indexOf(file);
          const newFileList = fileList.slice();
          newFileList.splice(index, 1);
          return {
            fileList: newFileList,
          };
        });
      },
      beforeUpload: (file) => {
        this.setState(({ fileList }) => ({
          fileList: [...fileList, file],
        }));
        return false;
      },
      fileList: this.state.fileList,
      onChange: this.handleChange,
      accept:accept
    };
    return (
      <Modal className="importer"
             visible={visible}
             onCancel={this.onCancel}
             onOk={this.handleOk}
             afterClose={this.handleAfterClose}
             title={title}
             confirmLoading={uploading}
             okText={tabKey === 'UPDATE' ? messages('components.key478'/*导 入*/) : messages('components.key479'/*完 成*/)}
             cancelText={messages('common.cancel')/*取消*/}>
        <Tabs defaultActiveKey="UPDATE" activeKey={tabKey} onChange={(key) => {this.setState({ tabKey: key })}}>
          <TabPane tab={messages('components.key492'/*上传文件*/)} key="UPDATE" disabled={tabKey === 'SUCCESS'}>
            {this.props.createTableShow && (
              <div>
                <h3>{messages('components.key493'/*创建电子表格*/)}</h3>
                <Button size="small" type="primary" onClick={this.downloadTemplate} loading={this.state.downloading}>
                  {messages('components.key661',{arg1:fileName}/*下载{arg1}*/)}
                </Button><br/>
                1.{messages('components.key494'/*点击上方按钮*/)}<br/>
                2.{messages('components.key495'/*严格按照导入模板整理数据，检查必输事项是否缺少数据*/)}<br/>
                3.{messages('components.key496'/*保存文件*/)}<br/>
                <br/>
              </div>
            )}
            <h3>{messages('components.key662',{arg1:fileName}/*上传{arg1}*/)}</h3>
            1.{messages('components.key497'/*点击【选择文件】按钮*/)}<br/>
            2.{messages('components.key663',{arg1:fileName}/*选择你刚更新过的{arg1}，并点击确定*/)}<br/>
            3.{messages('components.key498'/*点击【导入】按钮*/)}<br/>
            <span style={{color: 'red', marginBottom: '5px'}}>4.{messages('components.key848')/*导入完成前,请勿关闭此窗口！*/}</span>
            <br/>
            <Upload {...props} >
              <Button>
                <Icon type="upload" /> {messages('components.key499'/*选择文件*/)}
              </Button>
            </Upload>
          </TabPane>
          <TabPane tab={messages('components.key500'/*导入结果*/)} key="SUCCESS" disabled={tabKey === 'UPDATE'}>
            {resultDom}
            {!resultDom && !isSpecial && <div>
              <div>{messages('components.key660',{arg1: result.successEntities || 0}/*导入成功：{arg1}条*/)}</div>
              <div>{messages('components.key664',{arg1: result.failureEntities || 0}/*导入失败：{arg1}条*/)}
                {result.failureEntities ? (
                  <a
                    style={{fontSize: 14, marginLeft: 10}} onClick={()=>this.switchingTab('UPDATE')}>（{messages('components.key501'/*请修改相应数据后，重新导入*/)}）</a>
                ) : ''}
              </div>
              {result.failureEntities > 10 && !noTransaction &&
              <div style={{marginTop: 10}}>
                <Icon type="exclamation-circle-o" style={{marginRight: 5, color: 'red'}}/>
                {messages('components.key502'/*导入失败超过10条，请下载错误信息查看详情*/)}
              </div>}
              {result.failureEntities ? (
                <div>
                  {!noTransaction && (
                    <a style={{display: 'block', textAlign: 'right', marginBottom: 6}}
                       onClick={this.downloadErrors}>{messages('components.key503'/*下载错误信息*/)}</a>
                  )}
                  {!isSpecial && (
                    <Table rowKey={record => record.index}
                           columns={errorColumns}
                           dataSource={errorData}
                           pagination={false}
                           scroll={{x: false, y: 170}}
                           bordered
                           size="small"/>
                  )}
                </div>
              ) : ''}
            </div>}
            {
              !resultDom && isSpecial && <div>
                {
                  result.failureEntities ?
                    <div>
                      <h3><span style={{color: 'red'}}>{messages('components.key849')/*导入失败！*/}</span>{messages('components.key850')/*（请修改相应数据后，重新导入）*/}</h3>
                      <a style={{display: 'block'}} onClick={this.downloadErrors}>{messages('components.key503'/*下载错误信息*/)}</a>
                    </div> : <h3><span style={{color: 'blue'}}>{messages('components.key851')/*导入成功！*/}</span></h3>
                }
              </div>
            }
          </TabPane>
        </Tabs>
      </Modal>
    );
  }
}

Importer.propTypes = {
  visible: React.PropTypes.bool,           //导入弹框是否可见
  templateUrl: React.PropTypes.string,    //模版下载接口
  uploadUrl: React.PropTypes.string,     //上传接口
  listenUrl: React.PropTypes.string,    //监听上传状态接口，不需要写transactionID变量
  errorUrl: React.PropTypes.string,    //错误信息下载接口，不需要写transactionID变量
  title: React.PropTypes.string,      //标题
  downFileName: React.PropTypes.string,  //下载文件名
  fileName: React.PropTypes.string,  //处理的文件名类型，如Excel文件
  accept: React.PropTypes.string,  //文件上传类型
  onOk: React.PropTypes.func,       //导入成功回调
  tabKey: React.PropTypes.string,  //导入文件||导入结果页
  callBackResult: React.PropTypes.func,//导入结果通知
  isImporterResultDom: React.PropTypes.bool,//是否定制化导入结果DOM
  downFileExtension: React.PropTypes.string,    //下载模板文件后缀
  afterClose: React.PropTypes.func, //关闭后的回调
  noTransaction: React.PropTypes.bool,  //老版接口，非transaction规则的
  uploadParams: React.PropTypes.object, //上传接口的参数
  isSpecial: React.PropTypes.bool,
  haveConfirm: React.PropTypes.bool,//是否需要二次确认
};

Importer.defaultProps = {
  title: messages('common.import')/*'导入'*/,
  downFileName: messages('components.key504'/*导入文件*/),
  fileName: messages('components.key505'/*Excel电子表格*/),
  listenUrl: `${config.budgetUrl}/api/budget/batch/transaction/logs`,
  createTableShow: true,//创建表格示例是否显示
  isImporterResultDom:false,
  haveConfirm: false,//是否需要二次确认
  listentSwitch:false,//上传文件后直接回调
  callBackResult: ()=>{},//回调异步结果
  downFileExtension:'.xlsx',
  onOk: () => {},
  afterClose: () => {},
  noTransaction: false,
  isSpecial: false
};

function mapStateToProps() {
  return {}
}

export default connect(mapStateToProps)(Importer);
